import { SortFilter, SortFilterList2 } from '@/components/product/StandProductSort';
import StandSearchProduct from '@/components/StandSearchProduct';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { View } from '@tarojs/components';
import { useRouter } from '@tarojs/taro';
import React, { useCallback } from 'react';
import { connect } from 'react-redux';
import styles from './index.module.scss';

// sort 1 更新倒序  2 销量倒序 3 价格正序  4 价格倒序
function transformSort(sort) {
  switch (sort) {
    case SortFilter.newProduct:
      return 1;
    case SortFilter.sales:
      return 2;
    case SortFilter.up:
      return 3;
    case SortFilter.down:
      return 4;
    default:
      return 1;
  }
}

const SearchResult = ({
  dispatch,
  loading,
  searchResultList = [],
  searchResultFinished = false,
}) => {
  const isLoading = useShowLoading(loading, ['otherApi/getSearchResultModel']);

  const { params: { keywords = '' } = {} } = useRouter();

  const getNextList = useCallback(({ value, sort, ...rest }) => {
    return dispatch({
      type: 'otherApi/getSearchResultModel',
      payload: { keywords: value, pageSize: 20, sort: transformSort(sort), ...rest },
    });
  }, []);

  return (
    <View className={styles.SearchResult}>
      <StandSearchProduct
        searchProps={{
          defaultValue: keywords,
          onNext: getNextList,
        }}
        sortProps={{
          defaultValue: SortFilter.newProduct,
          customSortFilterList: SortFilterList2,
        }}
        productProps={{
          list: searchResultList,
          isFinished: searchResultFinished,
          isLoading,
        }}
      />
    </View>
  );
};

export default connect(({ loading, otherApi }) => ({
  loading,
  searchResultList: otherApi.searchResultList,
  searchResultFinished: otherApi.searchResultFinished,
}))(SearchResult);
